LIBS = ../libs
TOOLS = ../tools
BUILD = ../build
SRC = .

KERNEL_SOURCES+= $(shell find $(SRC)/kernel/ -name "*.asm")
KERNEL_SOURCES+= $(shell find $(SRC)/kernel/ -name "*.c")
KERNEL_SOURCES+= $(shell find $(SRC)/drivers/ -name "*.c")
KERNEL_SOURCES+= $(shell find $(SRC)/fs/ -name "*.c")
KERNEL_SOURCES:= $(strip ${KERNEL_SOURCES})

KERNEL_OBJECTS = \
	$(patsubst $(SRC)/%, $(BUILD)/%, \
	$(patsubst %.asm, %.o, \
	$(patsubst %.c, %.o, $(KERNEL_SOURCES))))

INCLUDE = -I $(SRC)/include

CFLAGS+= -m32
CFLAGS+= -march=pentium
CFLAGS+= -fno-builtin
CFLAGS+= -nostdinc
CFLAGS+= -fno-pic
CFLAGS+= -fno-pie
CFLAGS+= -nostdlib
CFLAGS+= -fno-stack-protector
CFLAGS+= -Wno-incompatible-pointer-types
CFLAGS+= -Werror
CFLAGS:=$(strip ${CFLAGS})

MULTIBOOT2:=0x18000
ENTRYPOINT = $(shell $(TOOLS)/elfpoint $(BUILD)/kernel.bin)
KERNELSIZE = $$(stat -c%s "$(BUILD)/kernel.raw.bin")

$(BUILD)/boot/loader.bin: $(SRC)/boot/loader.asm $(BUILD)/kernel.raw.bin
	$(shell mkdir -p $(dir $@))
	nasm -f bin $< -o $@ -DENTRYPOINT=$(ENTRYPOINT) -DKERNEL_SIZE=$(KERNELSIZE)

$(BUILD)/boot/%.bin: $(SRC)/boot/%.asm
	$(shell mkdir -p $(dir $@))
	nasm -f bin $< -o $@

$(BUILD)/%.o: $(SRC)/%.c
	$(shell mkdir -p $(dir $@))
	gcc -c -g $(INCLUDE) $(CFLAGS) $< -o $@

$(BUILD)/%.o: $(SRC)/%.asm
	$(shell mkdir -p $(dir $@))
	nasm -f elf32 -g $< -o $@

$(BUILD)/kernel.bin: \
	$(KERNEL_OBJECTS) \
	$(BUILD)/builtin/sh.o \
	$(BUILD)/lib/string.o \
	$(BUILD)/lib/syscall.o \
	$(BUILD)/lib/stdlib.o \
	$(BUILD)/lib/vsprintf.o \
	$(BUILD)/lib/bitmap.o \
	$(BUILD)/lib/list.o \
	$(BUILD)/lib/fifo.o \
	$(BUILD)/lib/stderror.o \
	$(BUILD)/lib/printf.o \
	$(BUILD)/lib/psf.o \

	ld -static -m elf_i386 $^ -o $@ -Ttext=0x20040 --section-start=.multiboot2=$(MULTIBOOT2)

$(BUILD)/kernel.raw.bin: $(BUILD)/kernel.bin
	objcopy -g -O binary $< $@

$(BUILD)/kernel.map: $(BUILD)/kernel.bin
	nm $< | sort > $@

$(BUILD)/lib/libc.o: \
	$(BUILD)/lib/crt.o \
	$(BUILD)/lib/crt1.o \
	$(BUILD)/lib/string.o \
	$(BUILD)/lib/syscall.o \
	$(BUILD)/lib/stdlib.o \
	$(BUILD)/lib/vsprintf.o \
	$(BUILD)/lib/bitmap.o \
	$(BUILD)/lib/list.o \
	$(BUILD)/lib/fifo.o \
	$(BUILD)/lib/stderror.o \
	$(BUILD)/lib/printf.o \

	ld -m elf_i386 -r $^ -g -o $@

BUILTIN_APPS = \
	$(BUILD)/builtin/ls \
	$(BUILD)/builtin/pwd \
	$(BUILD)/builtin/hello \
	$(BUILD)/builtin/cat \
	$(BUILD)/builtin/counter \
	$(BUILD)/builtin/echo \
	$(BUILD)/builtin/touch \
	$(BUILD)/builtin/readlink \
	$(BUILD)/builtin/getdents \
	$(BUILD)/builtin/rename \
	$(BUILD)/builtin/aux \
	$(BUILD)/builtin/mmap_test \

$(BUILD)/builtin/%: $(BUILD)/builtin/%.o $(BUILD)/lib/libc.o
	$(shell mkdir -p $(dir $@))
	ld -m elf_i386 -static -g $^ -o $@ -Ttext 0x8049000

$(BUILD)/builtin/hello: $(SRC)/builtin/hello.c
	$(shell mkdir -p $(dir $@))
	gcc -m32 -static -march=pentium $< -o $@

.PHONY: clean
clean:
	rm -rf $(BUILD)

include utils/image.mk
include utils/cmd.mk